package com.zjpavt.client.hal;

import com.zjpavt.client.nativemethod.JnIMethod;
import com.zjpavt.client.page.pageunit.ScreenLine;
import com.zjpavt.client.page.pageunit.ScreenPage;
import com.zjpavt.client.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


/**
 * 设备显示屏，单例模式
 *
 * @author cjp
 */
public class LedScreen {
    private static final Logger log = LoggerFactory.getLogger(LedScreen.class);
    private static final LedScreen instance = new LedScreen();
    /**
     * 换行符
     */
    public static final char DIVIDER_CHAR = '$';
    /**
     * 屏幕的高
     */
    public static final int SCREEN_HEIGHT = 4;
    /**
     * 屏幕的宽
     */
    public static final int SCREEN_WIDTH = 15;


    private LedScreen() {
    }

    public void setText(String text) {
        JnIMethod.printText(text);
    }

    /**
     * 按照行来设置
     * 允许长度超过4行 不计入
     * @param lineList 每行的list
     */
    public String setText(List<ScreenLine> lineList) {
        int lineNum = lineList.size();
        if (lineNum > SCREEN_HEIGHT) {
            lineNum = SCREEN_HEIGHT;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lineNum; i++) {
            sb.append(lineList.get(i).getLineContent());
            //末行不允许有换行符
            if (!isEndLine(i + 1)) {
                sb.append(DIVIDER_CHAR);
            }
        }
        JnIMethod.printText(sb.toString());
        return sb.toString();
    }

    /**
     * 按照页来设置
     * @param screenPage
     */
    public String setText(ScreenPage screenPage) {
        JnIMethod.printText(screenPage.getPageContent());
        return screenPage.getPageContent();
    }

    private boolean isEndLine(int lineNum) {
        return lineNum == SCREEN_HEIGHT;
    }

    /**
     * 指定位置输出(覆盖)
     *
     * @param x 行
     * @param y 列
     * @param text 内容
     */
    public void setText(int x, int y, String text) {
        if (x >= LedScreen.SCREEN_WIDTH || y >= LedScreen.SCREEN_HEIGHT) {
            log.error("x or y out of screen size");
            return;
        }
        //Jni只支持单位输出 所以按顺序输出
        if (!StringUtil.isNullOrEmpty(text)) {
            for (int i = 0; i < text.length(); i++) {
                if (x + i < LedScreen.SCREEN_WIDTH) {
                    JnIMethod.printTextWithPos(x + i, y, text.charAt(i));
                }
            }
        } else {
            log.error("text cannot be empty");
        }
    }

    /**
     * @return 输出屏幕（刷新，单例）
     */
    public static final LedScreen getInstance() {
        return instance;
    }


}
